# -*- coding: utf-8 -*-
# Echo server program

## todo: mettere a posto l'indentazione

import socket
import sys
import thread
from pyhomeClass import *

class socketClass(PyHomeClass):
    HOST = None               
    PORT = 2008
    
    s = None    
    def __init__(self):
		#PyHomeClass.parseConfigFile(self, "mods/socketnotify.conf")
		#HOST=PyHomeClass.confvars['HOST']
		#PORT=PyHomeClass.confvars['PORT']
        for res in socket.getaddrinfo(self.HOST, self.PORT, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
            af, socktype, proto, canonname, sa = res  
            try:
                self.s = socket.socket(af, socktype, proto)
            except socket.error, msg:
                self.s = None
                continue
            try:
                self.s.bind(sa)
                self.s.listen(3)
            except socket.error, msg:
                self.s.close()
                self.s = None
                continue
            break
        if self.s is None:
            print 'Error - could not open socket'
            sys.exit(1)

        #conn_v = []
        #addr_v = []
    connections = {}

    def initConnections(self):
        try:
           while 1:    
              conn, addr = self.s.accept()
              #print conn, addr
              #conn_v.append(conn) #not used
              #addr_v.append(addr)
              print 'Connected by', addr
              #conn_v[0].send("sei Ivan!")
              print "Waiting for hostname..."
              data = conn.recv(1024)
              if not data: break
              print data
              self.connections[data] = [conn, addr]
              self.connections[data][0].send("Connected!")
              self.sender(data,"Welcome to "+socket.gethostname())
              thread.start_new_thread(self.loop, (data,))
              #d = raw_input("To send: ")
              #conn.send(d)
              #conn.close()
              #print "closing connection..."
              print self.connections
        except KeyboardInterrupt:
           self.s.close()
           sys.exit(0)
          
    def printTest(self):
	    print "Funziona!"

    def sender(self, hostname, data):
		self.connections[hostname][0].send(data)

    def loop(self, hostname):
   		print "eccomi "+hostname
		print self.connections
		data = ""

		while 1:
		   try:
		      data = self.connections[hostname][0].recv(1024)
		   except KeyError: break
		   if not data: break
		   print hostname+": "+data
		   if data=="BYE":
		      del self.connections[hostname]
		      print hostname+" disconnected!"
		   elif data=="TEST":
		      print "Test REQUEST by "+hostname
		      self.sender(hostname,"Test OK")
		   print self.connections
         
    def closeSocket(self):
        self.s.close()

def notifystart():
    tc = socketClass()
    tc.initConnections()  
